package com.wmlive.hhvideo.heihei.mainhome.viewholder;

import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.airbnb.lottie.LottieAnimationView;
import com.wmlive.hhvideo.dcijkplayerlib.DcIjkPlayer;
import com.wmlive.hhvideo.dcijkplayerlib.Proxy;
import com.wmlive.hhvideo.heihei.beans.main.Author;
import com.wmlive.hhvideo.heihei.beans.main.ShortVideoItem;
import com.wmlive.hhvideo.heihei.beans.main.UserFanRelation;
import com.wmlive.hhvideo.heihei.login.AccountUtil;
import com.wmlive.hhvideo.heihei.mainhome.adapter.RecommendNewAdapter;
import com.wmlive.hhvideo.heihei.mainhome.fragment.RecommendFragmentNew;
import com.wmlive.hhvideo.heihei.mainhome.presenter.ShortVideoViewCallback;
import com.wmlive.hhvideo.utils.KLog;
import com.wmlive.hhvideo.utils.MyClickListener;
import com.wmlive.hhvideo.utils.ToastUtil;
import com.wmlive.hhvideo.utils.imageloader.GlideLoader;
import com.wmlive.hhvideo.widget.MarqueeView;
import com.wmlive.hhvideo.widget.refreshrecycler.BaseRecyclerViewHolder;

import butterknife.BindView;
import cn.wmlive.hhvideo.R;

/**
 * Created by lsq on 6/19/2017.
 * 单个视频的播放页面holder
 */

public class RecommendNewViewHolder extends BaseRecyclerViewHolder {
    @BindView(R.id.flPlayerContainer)
    public FrameLayout flPlayerContainer;
    @BindView(R.id.ivCover)
    public ImageView ivCover;
    @BindView(R.id.viewMusicName)
    MarqueeView viewMusicName;
    @BindView(R.id.tvMusicDesc)
    public TextView tvMusicDesc;
    @BindView(R.id.tvUser)
    public TextView tvUser;
    @BindView(R.id.llUser)
    public LinearLayout llUser;
    @BindView(R.id.tvTag)
    public TextView tvTag;
    @BindView(R.id.tvTopic)
    public TextView tvTopic;
    @BindView(R.id.ivFollow)
    public ImageView ivFollow;
    @BindView(R.id.ivLike)
    public ImageView ivLike;
    @BindView(R.id.tvLikeCount)
    public TextView tvLikeCount;
    @BindView(R.id.ivComment)
    public ImageView ivComment;
    @BindView(R.id.ivShare)
    public ImageView ivShare;
    @BindView(R.id.ivCdCover)
    public ImageView ivCdCover;
    @BindView(R.id.llRightPanel)
    public LinearLayout llRightPanel;
    @BindView(R.id.tvCommentCount)
    public TextView tvCommentCount;
    @BindView(R.id.ivUserAvatar)
    public ImageView ivUserAvatar;
    @BindView(R.id.rlFollow)
    public RelativeLayout rlFollow;
    @BindView(R.id.llMusicName)
    public LinearLayout llMusicName;
    public LottieAnimationView lavAnimView;
    @BindView(R.id.iv_player_status)
    ImageView ivPlayStatus;
    @BindView(R.id.iv_loading)
    ImageView ivLoading;
    @BindView(R.id.rlComment)
    RelativeLayout rlComment;
    private Animator loadingAnimator;


    private int position;

    private ShortVideoItem shortVideoItem;

    private ShortVideoViewCallback shortVideoViewCallback;
    private Author author;

    private Context context;
    private Animator loveAnimator;
    private Animator cdAnimator;
    private int videoType;

    public RecommendNewViewHolder(ViewGroup parent, int layoutId) {
        super(parent, layoutId);
        context = parent.getContext();
    }

    public void initData(int videoType, int position, ShortVideoItem item,
                         ShortVideoViewCallback clickListener, final RecommendNewAdapter recommendNewAdapter) {
        KLog.i("======ViewHolder initData:" + position);
        this.videoType = videoType;
        this.position = position;
        this.shortVideoViewCallback = clickListener;
//        if (null != recommendNewAdapter && null != recommendNewAdapter.getDataContainer()) {
//            item = recommendNewAdapter.getDataContainer().get(position);
//        }
        shortVideoItem = (item == null ? new ShortVideoItem() : item);
        shortVideoItem.setLoaded(false);
        setVideoCover(shortVideoItem.getOpus_cover());   //设置视频的封面
        GlideLoader.loadCircleImage(shortVideoItem.getMusic_album_cover(),
                ivCdCover, R.drawable.bg_search_music_default);//设置音乐的封面

        rlComment.setVisibility((videoType == RecommendFragmentNew.TYPE_RECOMMEND
                || videoType == RecommendFragmentNew.TYPE_FOLLOW) ? View.GONE : View.VISIBLE);

        initVideoLoading();


        ivPlayStatus.setVisibility(View.GONE);
        ivLoading.setVisibility(View.GONE);

        if (!TextUtils.isEmpty(shortVideoItem.getWonderful_tag())) {//设置推荐的标签
            tvTag.setVisibility(View.VISIBLE);
            tvTag.setText(shortVideoItem.getWonderful_tag());
        } else {
            tvTag.setVisibility(View.GONE);
        }

        if (!TextUtils.isEmpty(shortVideoItem.getTopic_name())) {//设置话题的标签
            tvTopic.setVisibility(View.VISIBLE);
            tvTopic.setText(shortVideoItem.getTopic_name());
        } else {
            tvTopic.setVisibility(View.GONE);
        }

        author = (shortVideoItem.getUser() == null ? new Author() : shortVideoItem.getUser());
        if (!TextUtils.isEmpty(author.getName())) {//设置用户Name
            llUser.setVisibility(View.VISIBLE);
            tvUser.setVisibility(View.VISIBLE);
            tvUser.setText(author.getName());
        } else {
            llUser.setVisibility(View.GONE);
            tvUser.setVisibility(View.GONE);
        }

        if (!TextUtils.isEmpty(shortVideoItem.getTitle())) {//设置用户的描述
            tvMusicDesc.setVisibility(View.VISIBLE);
            tvMusicDesc.setText(shortVideoItem.getTitle());
        } else {
            tvMusicDesc.setVisibility(View.GONE);
        }

        if (!TextUtils.isEmpty(author.getCover_url())) {//设置用户的头像
            GlideLoader.loadCircleImage(author.getCover_url(), ivUserAvatar, R.drawable.find_bg_user_default);
        }
        tvCommentCount.setText(String.valueOf(shortVideoItem.getComment_count()));
        setViewClickListener();
        if (shortVideoItem.getIs_delete() == 0) {
            if (Proxy.get().getProxyServer() != null
                    && Proxy.get().getProxyServer().isCached(shortVideoItem.getOpus_path())) {//本地已缓存
                dismissVideoLoading();
            } else {
                showVideoLoading();
            }
        } else {
            dismissVideoLoading();
        }
        setCommentCount();
        setLike(false);
        if (videoType == RecommendFragmentNew.TYPE_SINGLE_WORK) {
            showFollow();
            getRootView().postDelayed(new Runnable() {
                @Override
                public void run() {
                    recommendNewAdapter.forcePlay(false);
                }
            }, 300);
        }

        itemView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                KLog.v("vhawk", "itemView onTouch");
                return false;
            }
        });
    }


    public void viewVisible() {
        // 该控件需每次页面可见时重新赋值，每次页面不可见时销毁
        lavAnimView = (LottieAnimationView) itemView.findViewById(R.id.lavAnimView);
        initMusicBgAnimator();
        initCdAnimator();
        if (!TextUtils.isEmpty(shortVideoItem.getMusic_name())) {
            llMusicName.setVisibility(View.VISIBLE);
            viewMusicName.setTextContent(shortVideoItem.getMusic_name());
        } else {
            llMusicName.setVisibility(View.GONE);
        }
    }

    //设置视频封面是否可见
    public void setCoverVisible(boolean show) {
        ivCover.setVisibility(show ? View.VISIBLE : View.GONE);
    }

    private void setViewClickListener() {
        ivUserAvatar.setOnClickListener(clickListener);
        tvUser.setOnClickListener(clickListener);
        ivFollow.setOnClickListener(clickListener);
        ivLike.setOnClickListener(clickListener);
        ivComment.setOnClickListener(clickListener);
        ivShare.setOnClickListener(clickListener);
        ivCdCover.setOnClickListener(clickListener);
        llMusicName.setOnClickListener(clickListener);
        tvTopic.setOnClickListener(clickListener);
        rlComment.setOnClickListener(clickListener);
        viewMusicName.setOnClickListener(clickListener);
    }

    //设置评论数
    public void setCommentCount() {
        tvCommentCount.setText(String.valueOf(shortVideoItem.getComment_count()));
    }

    //设置点赞状态
    public void setLike(boolean showAnim) {
        tvLikeCount.setText(String.valueOf(shortVideoItem.getLike_count()));
        ivLike.setImageResource(shortVideoItem.is_like() ? R.drawable.icon_home_like_sel : R.drawable.icon_home_like);
        if (showAnim) {
            showLoveAnim(shortVideoItem.is_like());
        }
    }

    private void showLoveAnim(boolean like) {
        if (like) {
            ivLike.setImageResource(R.drawable.icon_home_like_sel);
            loveAnimator = AnimatorInflater.loadAnimator(context, R.animator.love_anim);
            loveAnimator.setInterpolator(new LinearInterpolator());
            loveAnimator.setTarget(ivLike);
            loveAnimator.start();
        } else {
            ivLike.setImageResource(R.drawable.icon_home_like);
        }
    }

    //显示关注
    public void showFollow() {
        if (shortVideoItem.getUser() != null) {
            rlFollow.setVisibility(View.VISIBLE);
            if (shortVideoItem.getUser().getRelation() == null) {
                shortVideoItem.getUser().setRelation(new UserFanRelation());
            }
            ivFollow.setVisibility((AccountUtil.getUserId() == shortVideoItem.getOwner_id()
                    || shortVideoItem.getUser().getRelation().isIs_follow()) ? View.INVISIBLE : View.VISIBLE);
        } else {
            rlFollow.setVisibility(View.INVISIBLE);
        }
    }

    public void attachVideoView(DcIjkPlayer ijkPlayer) {
        ViewGroup viewGroup = (ViewGroup) ijkPlayer.getParent();
        if (viewGroup != null) {
            KLog.i("=======移除父布局中的播放器");
            viewGroup.removeAllViews();
        }
        KLog.i("=======附加播放器到viewholder");
        flPlayerContainer.removeAllViews();
        flPlayerContainer.addView(ijkPlayer);
    }

    //设置关注用户
    public void setFollow() {
        if (shortVideoItem.getUser() != null) {
//            rlFollow.setVisibility(View.VISIBLE);
            if (shortVideoItem.getUser().getRelation() == null) {
                shortVideoItem.getUser().setRelation(new UserFanRelation());
            }
            shortVideoItem.getUser().getRelation().setIs_follow(true);
//            ivFollow.setVisibility(View.INVISIBLE);
        } else {
//            rlFollow.setVisibility(View.INVISIBLE);
        }
    }

    //设置封面
    public void setVideoCover(String url) {
        ivCover.setVisibility(View.VISIBLE);
        GlideLoader.loadImage(url, ivCover, R.drawable.icon_bg_video_default);
    }

    private void initMusicBgAnimator() {
        if (lavAnimView != null) {
            lavAnimView.setImageAssetsFolder("images");
            lavAnimView.loop(true);
            lavAnimView.setAnimation("phonetic_symbol.json");
        }
    }

    private void initCdAnimator() {
        cdAnimator = AnimatorInflater.loadAnimator(context, R.animator.music_anim);
        cdAnimator.setInterpolator(new LinearInterpolator());
        cdAnimator.setTarget(ivCdCover);
    }

    private MyClickListener clickListener = new MyClickListener() {
        @Override
        protected void onMyClick(View v) {
            if (null != clickListener) {
                if (shortVideoItem.getId() > 0) {
                    switch (v.getId()) {
                        case R.id.ivUserAvatar:
                        case R.id.tvUser:
                            if (author.getId() > 0) {
                                shortVideoViewCallback.onUserAvatarClick(AccountUtil.getUserId() == author.getId(), author.getId());
                            } else {
                                ToastUtil.showToast(R.string.hintErrorDataDelayTry);
                            }
                            break;
                        case R.id.ivFollow:
                            if (shortVideoItem.getUser() != null && shortVideoItem.getUser().getId() > 0) {
                                shortVideoViewCallback.onFollowClick(position, shortVideoItem.getId(), shortVideoItem.getUser().getId());
                            } else {
                                ToastUtil.showToast(R.string.hintErrorDataDelayTry);
                            }
                            break;
                        case R.id.ivLike:
                            if (shortVideoItem.getIs_delete() == 1) {
                                ToastUtil.showToast(R.string.stringWorkDeleted);
                                return;
                            }
                            shortVideoViewCallback.onLikeClick(position, shortVideoItem.getId());
                            break;
                        case R.id.ivComment://显示评论列表
                            if (shortVideoItem.getIs_delete() == 1) {
                                ToastUtil.showToast(R.string.stringWorkDeleted);
                                return;
                            }
                            shortVideoViewCallback.onCommentListShow(position, true, shortVideoItem.getComment_count(), shortVideoItem.getId());
                            break;
                        case R.id.ivShare:
                            if (shortVideoItem.getIs_delete() == 1) {
                                ToastUtil.showToast(R.string.stringWorkDeleted);
                                return;
                            }
                            if ((shortVideoItem.getShare_info() != null
                                    && (!TextUtils.isEmpty(shortVideoItem.getShare_info().getShare_url())))) {
                                shortVideoViewCallback.onShareClick(RecommendNewViewHolder.this.position, shortVideoItem.getId(),
                                        AccountUtil.isLogin() && (AccountUtil.getUserId() == author.getId()),
                                        shortVideoItem.getShare_info());
                            } else {
                                ToastUtil.showToast(R.string.hintErrorDataDelayTry);
                            }
                            break;
                        case R.id.ivCdCover:
                        case R.id.llMusicName:
                        case R.id.viewMusicName:
                            shortVideoViewCallback.onMusicClick(shortVideoItem.getMusic_id());
                            break;
                        case R.id.tvTopic:
                            shortVideoViewCallback.onTopicClick(shortVideoItem.getTopic_id());
                            break;
                        case R.id.rlComment:
                            if (shortVideoItem.getIs_delete() == 1) {
                                ToastUtil.showToast(R.string.stringWorkDeleted);
                                return;
                            }
                            shortVideoViewCallback.onOpenCommentSend(position, shortVideoItem.getId());
                            break;
                    }
                } else {
                    ToastUtil.showToast(R.string.hintErrorDataDelayTry);
                }
            }
        }
    };


    public void showFollowAnim() {
        AnimationDrawable animationDrawable = ((AnimationDrawable) ivFollow.getDrawable());
        animationDrawable.setOneShot(true);
        animationDrawable.start();
        ivFollow.setClickable(false);
    }

    public void startMusicAnim() {
        // 跑马灯
        if (viewMusicName != null) {
            viewMusicName.start();
        }

        // 音符动画
        if (lavAnimView != null && !lavAnimView.isAnimating()) {
            lavAnimView.setVisibility(View.VISIBLE);
            lavAnimView.playAnimation();
        }
        // 音乐旋转动画
        if (cdAnimator != null && !cdAnimator.isRunning()) {
            cdAnimator.start();
        }

    }

    public void resumeMusicAnim() {
        if (viewMusicName != null) {
            viewMusicName.resume();
        }

        if (lavAnimView != null && !lavAnimView.isAnimating()) {
            lavAnimView.resumeAnimation();
            lavAnimView.setVisibility(View.VISIBLE);
        }

        if (cdAnimator != null && cdAnimator.isPaused()) {
            cdAnimator.resume();
        }
    }

    public void pauseMusicAnim() {
        if (viewMusicName != null) {
            viewMusicName.pause();
        }

        if (lavAnimView != null && lavAnimView.isAnimating()) {
            lavAnimView.pauseAnimation();
            lavAnimView.setVisibility(View.INVISIBLE);
        }

        if (cdAnimator != null) {
            cdAnimator.pause();
        }
    }

    public void showVideoLoading() {
        ivLoading.setVisibility(View.VISIBLE);
        initVideoLoading();
        loadingAnimator.start();
    }

    private void initVideoLoading() {
        loadingAnimator = AnimatorInflater.loadAnimator(context, R.animator.loading);
        loadingAnimator.setInterpolator(new LinearInterpolator());
        loadingAnimator.setTarget(ivLoading);
    }

    public void dismissVideoLoading() {
        if (loadingAnimator != null) {
            loadingAnimator.cancel();
            loadingAnimator = null;
        }
        ivLoading.clearAnimation();
        ivLoading.setVisibility(View.GONE);
    }

    //是否显示播放按钮
    public void setPlayIcon(boolean isPlaying) {
        ivPlayStatus.setVisibility(isPlaying ? View.GONE : View.VISIBLE);
    }


    /**
     * 释放资源
     */
    public void releaseMusicAnim() {
        if (null != viewMusicName) {
//            tvMusicName.clearAnimation();
//            nameAnim = null;
            viewMusicName.cancel();
        }

        if (lavAnimView != null) {
            if (lavAnimView.isAnimating()) {
                lavAnimView.cancelAnimation();
            }
            lavAnimView = null;
        }

        if (cdAnimator != null) {
            cdAnimator.cancel();
            cdAnimator = null;
            ivCdCover.clearAnimation();
        }
    }

    /**
     * 连续点击，播放屏幕点赞动画
     *
     * @param rawX
     * @param rawY
     */
    public void showLikeAnim(float rawX, float rawY) {

        if (!shortVideoItem.is_like()) {
            if (!TextUtils.isEmpty(AccountUtil.getToken())) {
                shortVideoViewCallback.onLikeClick(position, shortVideoItem.getId());
                shortVideoItem.setIs_like(true);
            }
        }

        //获取ivLike控件的屏幕坐标
        int[] location = new int[2];
        ivLike.getLocationOnScreen(location);
        int x = location[0];
        int y = location[1];
        KLog.v("vhawk", "==== rawX = " + rawX + " rawY = " + rawY);

        final ImageView imageView = addLikeAnimVIew((int) rawX, (int) rawY);

        Animator heartScaleAnim = AnimatorInflater.loadAnimator(context, R.animator.heart_scale_anim);
        heartScaleAnim.setTarget(imageView);

        final ObjectAnimator translationXAnim = ObjectAnimator
                .ofFloat(imageView, "translationX", 0, x - rawX)
                .setDuration(160);
        final ObjectAnimator translationYAnim = ObjectAnimator
                .ofFloat(imageView, "translationY", 0, y - rawY)
                .setDuration(160);

        final ObjectAnimator scaleXAnim = ObjectAnimator.ofFloat(imageView, "scaleX", 0.8f, 0.4f)
                .setDuration(160);
        final ObjectAnimator scaleYAnim = ObjectAnimator.ofFloat(imageView, "scaleY", 0.8f, 0.4f)
                .setDuration(160);

        heartScaleAnim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                translationXAnim.start();
                translationYAnim.start();
                scaleXAnim.start();
                scaleYAnim.start();
            }
        });

        translationXAnim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                ((RelativeLayout) itemView).removeView(imageView);
            }
        });

        heartScaleAnim.start();
    }

    /**
     * 动态添加连续点击动画的view
     *
     * @param rawX 动态添加view的横坐标
     * @param rawY 动态添加view的纵坐标
     * @return
     */
    @NonNull
    private ImageView addLikeAnimVIew(int rawX, int rawY) {
        final ImageView imageView = new ImageView(getRootView().getContext());
        imageView.setImageResource(R.drawable.icon_homepage_bigheart);

        int viewWidth = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        int viewHeight = View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED);
        imageView.measure(viewWidth, viewHeight);
        float width = imageView.getMeasuredWidth();
        float height = imageView.getMeasuredHeight();

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.leftMargin = (int) (rawX - width * 0.3);
        layoutParams.topMargin = (int) (rawY - height * 0.3);
        imageView.setLayoutParams(layoutParams);
        ((RelativeLayout) itemView).addView(imageView);
        return imageView;
    }
}
